package com.song.workpool.taskimpl;

import java.util.Vector;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

import com.song.email.bean.Auth;
import com.song.email.bean.EmailInfo;
import com.song.email.bean.Work;
import com.song.email.core.AuthCenter;
import com.song.email.core.MailtoCenter;
import com.song.email.util.common.Config;
import com.song.email.util.common.Counter;
import com.song.email.util.email.SendMail;
import com.song.workpool.Task;

public class SendEmailTask  extends Task<Work> {
	private static Log log = LogFactory.getLog(SendEmailTask.class);
	private EmailInfo emailInfo = null;

	public SendEmailTask(Work work) {
		emailInfo = converWork2EmailInfo(work);
	}

	public void taskPerform() throws Exception {
		if(null != emailInfo){
			Vector<String> mailtoList = MailtoCenter.getInstance().getMailtoList();
			for (String mailto : mailtoList) {
				boolean isSendSuccess = false;
				emailInfo.setMailto(mailto);
				Auth auth = AuthCenter.getInstance().getAuth();
				emailInfo.setMailFrom(auth.getEmail());
				emailInfo.setPassword(auth.getPasswd());
				emailInfo.setUsername(auth.getUsername());
				emailInfo.setProtocolType(auth.getProtocolType());
				
				SendMail sendMail = new SendMail(emailInfo);
				
				isSendSuccess = sendMail.sendMail();
				if(!isSendSuccess){
					log.error("邮件发送失败,可能是auth不可用. 发件人:" 
							+ auth.getEmail() + "  主题:" + emailInfo.getSubject());
					for (int i=0;i<Config.failRetryTimes;i++) {
						auth = AuthCenter.getInstance().getAuth();
						emailInfo.setMailFrom(auth.getEmail());
						emailInfo.setPassword(auth.getPasswd());
						emailInfo.setUsername(auth.getUsername());
						emailInfo.setProtocolType(auth.getProtocolType());
						sendMail = new SendMail(emailInfo);
						isSendSuccess = sendMail.sendMail();
						
						if(!isSendSuccess){
							log.error("邮件发送失败,可能是auth不可用. 发件人:" 
									+ auth.getEmail() + "  主题:" + emailInfo.getSubject());
							Thread.sleep(Config.sendFrequency);
						}else{
							break;
						}
					}
				}
				if(isSendSuccess){
					Counter.setMailSendSuccessCount();
				}else{
					Counter.setMailSendFailCount();
				}
				
				Thread.sleep(Config.sendFrequency);
			}
		}
	}
	
	private EmailInfo converWork2EmailInfo(Work work){
		if(work == null){
			return null;
		}
		EmailInfo emailInfo = new EmailInfo();
		emailInfo.setAttachList(work.getAttachList());
		emailInfo.setContent(work.getContent());
		emailInfo.setSubject(work.getSubject());
		
		return emailInfo;
	}
}
